function [ output ] = buildFrequencySet_Core( cfg )
output = [];
EEG = pop_loadset('filename', cfg.Input.EegSetFilename);

if cfg.ProcessAllChannels
    selection = 1:length(EEG.chanlocs);
else
    tf = false(1, length(EEG.chanlocs));
    for i = 1:length(cfg.ChannelSelection)
        tf = tf | strcmp(cfg.ChannelSelection{i}, {EEG.chanlocs.labels});
    end
    selection = find(tf);
end

for elecNr = selection;
    data.channel = EEG.chanlocs(elecNr).labels;
    outputFilename = [cfg.Output.TfcDataFolder cfg.SubjectPrimaryPrefix ' ' data.channel ' ' cfg.EpochSetName ' Timefreq data.mat'];

    doTheTFStep = ~cfg.SkipIfAlreadyExists;
    if exist(outputFilename, 'file')
        disp(['Preloading existing data from "' outputFilename '"'])
        load(outputFilename);
        fileMustBeSaved = false;
        
        if isnumeric(data.epochs.nrOfEpochsFound), currentNr = data.epochs.nrOfEpochsFound; else currentNr = str2num(data.epochs.nrOfEpochsFound); end
        if currentNr ~= EEG.trials
            disp(['Nr of epochs in datafile (' num2str(currentNr) ') is not the same as nr of epochs in newer set (' num2str(EEG.trials) '): running TF again.']);
            doTheTFStep = true;
        end
    else
        doTheTFStep = true;
        fileMustBeSaved = true;
    end
    
    data.subject = cfg.SubjectPrimaryPrefix;
    data.epochs.name = cfg.EpochSetName;
    data.epochs.nrOfEpochsFound = EEG.trials;
    
    if doTheTFStep
        data.datecode = datecode;
        disp(['Timefreqqing channel ''' data.channel '''...']);
        dataToTF = squeeze(EEG.data(elecNr,:,:));
        if size(dataToTF,1) == 1, dataToTF = dataToTF'; end % In case there is only 1 trial, make sure the timefreq still gets times x trials (in this case change 1x5120 to 5120x1..)
        [data.tf data.freqs data.times data.itcvals] = timefreq(dataToTF, 512, 'ntimesout', 1000, 'freqs', [3 150], 'padratio', 2);
        if isempty(EEG.times), timesAdjust = EEG.xmin * 1000; else timesAdjust = min(EEG.times); end % Just in case there is only 1 trial (again)
        data.times = data.times + timesAdjust; % Correction, since timefreq fucks up the offset..
        fileMustBeSaved = true;
    else
        disp(['Skipping Timefreq for channel ''' data.channel ''' and condition ''' data.epochs.name '''...']);
        % Adjust times if needed..
        if min(data.times)>-2500
            if isempty(EEG.times), timesAdjust = EEG.xmin * 1000; else timesAdjust = min(EEG.times); end % Just in case there is only 1 trial (again)
            data.times = data.times + timesAdjust;
            fileMustBeSaved = true;
        end
    end
    
    if ~any(strcmp(fieldnames(data),'markers')) || doTheTFStep
        for epI = 1:data.epochs.nrOfEpochsFound
            epMarkers = EEG.event([EEG.event.epoch] == epI);
            if isempty(EEG.times), t = 1000*(EEG.xmin:1/EEG.srate:EEG.xmax); else t = EEG.times; end
            latsMs = t([epMarkers.latency] - (epI-1)*EEG.pnts);
            MARKERS = [];
            for epJ = 1:length(epMarkers)
                MARKERS(epJ).type = epMarkers(epJ).type;
                MARKERS(epJ).latencyMs = latsMs(epJ);
                [DTY DTI] = min(abs(data.times - latsMs(epJ)));
                MARKERS(epJ).latency = DTI;
            end
            data.markers{epI} = MARKERS;
        end
    end
    
    if fileMustBeSaved
        disp('Saving to file...')
        save(outputFilename, '-v7.3', 'data');
    else
        disp('File hasn''t changed, leaving it as it was.');
    end

    safeChannelName = data.channel;
    safeChannelName(safeChannelName == '-') = '_';
    output.TfcData.(safeChannelName).Channel = data.channel;
    output.TfcData.(safeChannelName).Filename = outputFilename;
    output.TfcData.(safeChannelName).Datecode = datecode;
    %         memory;
    
    clearvars -except fn x subjectinfo output dataFolder EEG tfc cfg;
end
clearvars -except fn x subjectinfo output dataFolder cfg;


end